public class Solution1325 {

    public static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    public TreeNode removeLeafNodes(TreeNode root, int target) {
        TreeNode treeNode=new TreeNode(-1,root,null);
        dfs(root,treeNode,target);
        return treeNode.left;
    }

    private void dfs(TreeNode root, TreeNode father, int target) {
        if (root==null){
            return;
        }
        dfs(root.left,root,target);
        dfs(root.right,root,target);
        if (root.left==null && root.right==null && root.val==target){
            if (father.left==root){
                father.left=null;
            }else {
                father.right=null;
            }
        }
    }

    public static void main(String[] args) {
        System.out.println(new Solution1325().removeLeafNodes(new TreeNode(1,new TreeNode(2,new TreeNode(2),null),new TreeNode(3,new TreeNode(2),new TreeNode(4))),2).left);
    }
}
